import { NotifyService } from '@abp/notify/notify.service';
import {
  Component,
  Injector,
  ViewChild,
  ViewEncapsulation
} from '@angular/core';
import { Http } from '@angular/http';
import { appModuleAnimation } from '@shared/animations/routerTransition';
import { AppComponentBase } from '@shared/common/app-component-base';
import {
  ToolingServiceProxy,
  ToolingListDto,
  ComboboxItemDto,
  Status2,
  Category2,
  Operation
} from '@shared/service-proxies/service-proxies';
import { FileDownloadService } from '@shared/utils/file-download.service';
import { LazyLoadEvent } from 'primeng/components/common/lazyloadevent';
import { Paginator } from 'primeng/components/paginator/paginator';
import { Table } from 'primeng/components/table/table';
import { CreateOrEditToolingModalComponent } from './create-or-edit-tooling-modal.component';
import { ActionToolingModalComponent } from './action-tooling-modal.component';
import { EditOutOrBackToolingModalComponent } from './edit-out-or-back-tooling-modal.component';
import * as moment from 'moment';

@Component({
  templateUrl: './tooling.component.html',
  encapsulation: ViewEncapsulation.None,
  animations: [appModuleAnimation()]
})
export class ToolingsComponent extends AppComponentBase {
  @ViewChild('createOrEditToolingModal')
  createOrEditToolingModal: CreateOrEditToolingModalComponent;
  @ViewChild('actionToolingModal')
  actionToolingModal: ActionToolingModalComponent;
  @ViewChild('editOutOrBackToolingModal')
  editOutOrBackToolingModal: EditOutOrBackToolingModalComponent;
  @ViewChild('dataTable') dataTable: Table;
  @ViewChild('paginator') paginator: Paginator;

  advancedFiltersAreShown = false;
  filterText = '';

  statuses: ComboboxItemDto[];
  categorys: ComboboxItemDto[];

  status: Status2 = undefined;
  category: Category2 = undefined;

  nowMoment = moment.utc();

  constructor(
    injector: Injector,
    private _http: Http,
    private _toolingServiceProxy: ToolingServiceProxy,
    private _notifyService: NotifyService,
    private _fileDownloadService: FileDownloadService
  ) {
    super(injector);
  }

  getToolings(event?: LazyLoadEvent) {
    if (this.primengTableHelper.shouldResetPaging(event)) {
      this.paginator.changePage(0);
      return;
    }

    this.primengTableHelper.showLoadingIndicator();

    this._toolingServiceProxy
      .getToolings(
        this.filterText,
        this.status,
        this.category,
        this.primengTableHelper.getSorting(this.dataTable),
        this.primengTableHelper.getMaxResultCount(this.paginator, event),
        this.primengTableHelper.getSkipCount(this.paginator, event)
      )
      .subscribe(result => {
        this.primengTableHelper.totalRecordsCount = result.totalCount;
        this.primengTableHelper.records = result.items;
        this.primengTableHelper.hideLoadingIndicator();
      });
  }

  reloadPage(): void {
    this.paginator.changePage(this.paginator.getPage());
  }

  exportToExcel(isOnlyTmpl: boolean): void {
    this._toolingServiceProxy
      .getToolingsToExcel(isOnlyTmpl)
      .subscribe(result => {
        this._fileDownloadService.downloadTempFile(result);
      });
  }

  onUpload(event) {
    let list = event as Array<any>;

    let toolings = list.map(el => {
      return {
        count: Number(el.数量),
        title: el.名称,
        categoryName: el.检定类别,
        classificationName: el.所属分类,
        subTitle: el.工装图号,
        isDrawing: el.有无图纸 === 'TRUE' || el.有无图纸 === '有',
        drawingCodes: el.产品图号,
        model: el.型号,
        stamp: el.钢印号,
        location: el.位置,
        manufactureDate: el.制造日期
          ? moment(el.制造日期).add(8, 'hour')
          : undefined,
        receiptTime: el.接收时间
          ? moment(el.接收时间).add(8, 'hour')
          : undefined,
        intoStockDate: el.入库日期
          ? moment(el.入库日期).add(8, 'hour')
          : undefined,
        manufacturer: el.制造单位,
        unit: el.计量单位,
        groupParts: el.组配件,
        certificate: el.有无合格证 === 'TRUE' || el.有无合格证 === '有',
        handover: el.有无交接单 === 'TRUE' || el.有无交接单 === '有',
        toolingRecord: el.有无履历卡 === 'TRUE' || el.有无履历卡 === '有',
        isVerificationCard: el.有无鉴定卡片,
        otherInfo: el.其他资料,
        toolingSource: el.工装来源,
        isNeedVerification:
          el.是否要周期检定 === 'TRUE' ||
          el.是否要周期检定 === '有' ||
          el.是否要周期检定 === '是',
        verificationDate: el.检定日期
          ? moment(el.检定日期).add(8, 'hour')
          : undefined,
        nextVerificationDate: el.检定有效期
          ? moment(el.检定有效期).add(8, 'hour')
          : undefined,
        maxLoad: el.最大载荷,
        belongTo: el.所属资产,
        responsible: el.责任人,
        technologist: el.工艺员,
        remark: el.备注
      };
    }) as Array<ToolingListDto>;

    this.message.confirm(
      '确认导入这' + list.length + '条数据吗？',
      this.l('AreYouSure'),
      isConfirmed => {
        if (isConfirmed) {
          this.primengTableHelper.showLoadingIndicator();
          this._toolingServiceProxy
            .importGeneralTools(toolings)
            .subscribe(result => {
              this.reloadPage();
              this.notify.success('导入数据成功');
            });
        }
      }
    );
  }

  deleteTooling(tooling: ToolingListDto): void {
    this.message.confirm(
      '确认删除设备(' + tooling.title + ')',
      this.l('AreYouSure'),
      isConfirmed => {
        if (isConfirmed) {
          this._toolingServiceProxy.deleteTooling(tooling.id).subscribe(() => {
            this.reloadPage();
            this.notify.success(this.l('SuccessfullyDeleted'));
          });
        }
      }
    );
  }

  showAction(type: Operation) {
    //console.log(type);
    this.actionToolingModal.show(type);
  }

  outStock(tooling: ToolingListDto, type: number) {
    this.editOutOrBackToolingModal.show(tooling, type, 1);
  }

  backStock(tooling: ToolingListDto) {
    this.editOutOrBackToolingModal.show(tooling, tooling.operation, 2);
  }

  goCar(tooling: ToolingListDto, type: number) {
    this._toolingServiceProxy.goCar(tooling.id, type).subscribe(() => {
      this.reloadPage();
      this.notify.success('加入成功');
    });
  }

  cancelCar(tooling: ToolingListDto) {
    this._toolingServiceProxy.cancelCar(tooling.id).subscribe(() => {
      this.reloadPage();
      this.notify.success('取消成功');
    });
  }
}
